<script lang="ts" setup>
import { toRefs, ref } from "vue";
import { Api } from "../../apis/index";
import { useRouter } from "vue-router";
import { DiscoverAllArticleType } from "@/typing";
import { getPrevMonthDate } from "@/utils/data-tools";
import { homeStoriesStore } from "@/store/index";
import LaudIcon from "@/components/icon/LaudIcon.vue";
import ShareIcon from "@/components/icon/ShareIcon.vue";
import { Toast } from 'vant';
import 'vant/es/toast/style';

const router = useRouter()
const store = homeStoriesStore();
const { updateArticle,updateIsDiscoverShow } = store;

const props = defineProps<{
    category: number
}>()

const { category } = toRefs(props);

let articleList = ref<Array<DiscoverAllArticleType>>([]);
let length = ref(0);
let month = ref('');
month.value = getMonthFunc();

const list = ref([]);
const loading = ref(false);
const finished = ref(false);
const isPicker = ref(false);

const currentDate = ref(new Date());
const minDate = ref<Date>();
const maxDate = ref<Date>();
minDate.value = new Date(2020, 0, 1);
maxDate.value = new Date(2022, 11, 1);


// 获取前一个月的信息
const getPrevDateStories = async () => {
    let prevDate = getPrevMonthDate(month.value);
    let prevMonth = getPrevMonthDate(month.value).substring(0, 7)

    month.value = prevDate;

    const { data } = await Api.getDiscoverArticleList(category.value, prevMonth)
    setTimeout(() => {

        // 加载状态结束
        loading.value = false;

        // 数据全部加载完成
        if (list.value.length >= 12) {
            finished.value = true;
        }
        articleList.value = [...articleList.value, data.data];

    }, 1000)
}

const onLoad = () => {
    getPrevDateStories();
};

render()
async function render() {
    Toast.loading({
        message: '加载中...',
        forbidClick: true,
    });

    const data = await Api.getDiscoverArticleList(category.value, month.value);
    articleList.value = [...articleList.value, data.data.data];
    length.value = articleList.value[0].length;
}

function formatter(type: string, val: string) {
    if (type === 'year') {
        return `${val}年`;
    }
    if (type === 'month') {
        return `${val}月`;
    }
    return val;
}

function getMonthFunc() {
    let date = new Date();
    let monthNum = date.getMonth() + 1;
    let monthStr = monthNum >= 10 ? '' + monthNum : '0' + monthNum;

    return date.getFullYear() + '-' + monthStr;
}

function goToRadioView(id: string, category: string, title: string) {
    updateArticle(id, category, title);
    router.push({ name: 'radio' })
}

function goToHpDetail(date: string) {
    updateIsDiscoverShow(true);
    router.push({ name: 'discover-hp', query: { date } })
}

function confirmFunc() {
    isPicker.value = false;
    let date = currentDate.value;
    let monthNum = date.getMonth() + 1;
    let monthStr = monthNum >= 10 ? '' + monthNum : '0' + monthNum;
    articleList.value = [];
    month.value = date.getFullYear() + '-' + monthStr;
    render();
}

function getTitleMonth() {
    let date = currentDate.value;
    let monthNum = date.getMonth() + 1;
    let monthStr = monthNum >= 10 ? '' + monthNum : '0' + monthNum;

    return date.getFullYear() + '年 ' + monthStr + '月';
}

function cancelFunc() {
    isPicker.value = false;
}

function showPicker() {
    isPicker.value = true;
}

function goToDetail(category: number, id: number, title: string) {
    if (category == 1 || category == 3) {
        updateArticle(String(id), String(category), title);

        router.push({
            name: 'article-detail'
        })
    }
}


</script>

<template>
    <div class="px-8 py-5 h-screen">
        <div @click="showPicker" v-show="!isPicker" class="text-size mb-5 flex justify-center"
            :class="category === 0 ? 'font-mb' : ''">
            <div>{{ getTitleMonth() }}</div>
            <img class="mt-2 ml-2 w-6 h-6" src="@/assets/share/arrow_down_black.png" alt="">
        </div>

        <van-popup v-model:show="isPicker" position="top" :style="{ height: '48%' }">
            <van-datetime-picker v-model="currentDate" type="year-month" title="选择年月" :min-date="minDate"
                :max-date="maxDate" :formatter="formatter" @confirm="confirmFunc" @cancel="cancelFunc" />
        </van-popup>

        <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">

            <div v-show="(length != 0)">
                <div v-for="(arr, i) in articleList" :key="i">
                    <div class="mb-20" :class="category === 0 ? 'cate-zero' : ''">
                        <div class="relative" v-for="(l, i) in arr" :key="i"
                            :class="category === 0 ? 'cate-zero-item' : ''">

                            <van-divider class=" w-full" :class="category == 0 ? 'month-line' : ''"
                                :style="{ color: '#aaa', borderColor: '#aaa' }" v-if="i == 0">{{
                                        l.maketime.substring(5, 7)
                                }}月</van-divider>

                            <div v-if="category !== 8 && category !== 0" class="flex mt-8 mb-12"
                                @click="goToDetail(category, l.id, l.title)">
                                <img class="w-24 rounded-2xl mr-5" :src="l.cover" alt="img">
                                <div class="w-4/5">
                                    <div class=" discover-title mt-2 mb-4 text-2xl">{{ l.title }}</div>
                                    <div class=" text-gray-400 ">{{ l.subtitle }}</div>
                                </div>
                            </div>

                            <div v-if="category === 0" class="mx-3 my-5 rounded-xl shadow"
                                @click="goToHpDetail(l.maketime.substring(0, 10))">
                                <img :src="l.cover" class="rounded-t-xl w-full" />
                                <div class="text-center text-gray-400 py-4"> {{ l.maketime.substring(0, 10) }}</div>
                            </div>

                            <div v-if="category === 8" class=" mt-8 mb-12">
                                <div class="relative" @click="goToRadioView(String(l.id), String(category), l.title)">
                                    <img class="mt-8  rounded-2xl" rounded-t-sm :src="l.cover" alt="img">

                                    <div class="absolute top-5 left-6 w-52 flex justify-between items-center">
                                        <img class="w-18 h-5" src="../../assets/card/one_radio_icon.png" alt="one">
                                        <div class="text-gray-200">{{ l.volume }}</div>
                                    </div>
                                    <div class=" absolute bottom-6 left-6 text-gray-100 text-3xl mt-8">{{ l.title }}
                                    </div>
                                    <img class="absolute bottom-6 right-6 w-14"
                                        src="@/assets/audio/feeds_radio_play.png" alt="img">
                                </div>

                                <div class="flex justify-between items-center pt-8 px-3">
                                    <div class="flex w-40 justify-between  ">
                                        <img class="rounded-full  w-14 h-14 " :src="l.author.web_url" alt="img">
                                        <div class="text-gray-400 mt-3">{{ l.author.user_name }}</div>
                                    </div>
                                    <div class="flex justify-between items-center">
                                        <LaudIcon :countNum="l.like_count" />
                                        <div class="ml-14">
                                            <ShareIcon :type="0" :shareList="l.share_list" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <img v-show="(length == 0)" class="w-80 ml-40 mt-52" src="@/assets/share/no_music_pic.png" alt="img" />
        </van-list>
    </div>
</template>

<style>
.discover-title {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

.cate-zero {
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;
}

.cate-zero-item {
    width: 50%;
}

.month-line {
    position: absolute;
    top: -20px;
    left: 85px;
}

.text-size {
    font-size: 15px !important;
    color: gray;
}

.font-mb {
    margin-bottom: 25px !important;
}
</style>